/**
 * Copyright (c) 2021 Coder League
 * All rights reserved.
 *
 * File：GoodService.java
 * History:
 *         2021年1月5日: Initially created, Chrise.
 */
package club.coderleague.cfss.service.good;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import club.coderleague.cfss.config.properties.FileUploadSettings;
import club.coderleague.cfss.dao.CybercafeDao;
import club.coderleague.cfss.dao.GoodDao;
import club.coderleague.cfss.dao.GoodPictureDao;
import club.coderleague.cfss.dao.SupplierDao;
import club.coderleague.cfss.domain.beans.GoodPictureUpdateRequest;
import club.coderleague.cfss.domain.beans.GoodSearcher;
import club.coderleague.cfss.domain.beans.GoodUpdateRequest;
import club.coderleague.cfss.domain.beans.ListGood;
import club.coderleague.cfss.domain.beans.UserSession;
import club.coderleague.cfss.domain.beans.ViewGoodDetail;
import club.coderleague.cfss.domain.beans.ViewListGood;
import club.coderleague.cfss.domain.entities.Goodpictures;
import club.coderleague.cfss.domain.entities.Goods;
import club.coderleague.cfss.domain.enums.EntityState;
import club.coderleague.cfss.domain.enums.PictureType;
import club.coderleague.cfss.exceptions.FileUploadException;
import club.coderleague.cfss.util.CommonUtil;
import club.coderleague.cfss.util.FileUtil;

/**
 * 商品服务。
 * @author Chrise
 */
@Service
public class GoodService {
	@Autowired
	private GoodDao goodDao;
	@Autowired
	private GoodPictureDao gpDao;
	@Autowired
	private CybercafeDao cybercafeDao;
	@Autowired
	private SupplierDao supplierDao;
	@Autowired
	private FileUploadSettings fuSettings;
	
	/**
	 * 加载商品管理列表数据。
	 * @author Chrise 2021年1月10日
	 * @param session 用户会话。
	 * @return 商品管理列表数据。
	 */
	public List<ListGood> loadMgrListData(UserSession session) {
		return this.goodDao.queryMgrListData(session.getOrgid(), this.fuSettings.getRootVirtual() + this.fuSettings.getGoodpicturePath());
	}
	
	/**
	 * 商品调价。
	 * @author Chrise 2021年1月12日
	 * @param goodid 商品标识。
	 * @param goodprice 商品价格。
	 */
	public void execAdjustPrice(long goodid, double goodprice) {
		int entitystate = (goodprice == 0.0) ? EntityState.VALID.getValue() : EntityState.ONSALE.getValue();
		
		Goods good = this.goodDao.getOne(goodid);
		good.setEntitystate(entitystate);
		good.setGoodprice(goodprice);
	}
	
	/**
	 * 加载商品管理商品数据。
	 * @author Chrise 2021年1月11日
	 * @param goodid 商品标识。
	 * @return 商品管理商品数据。
	 */
	public GoodUpdateRequest loadMgrGoodData(long goodid) {
		GoodUpdateRequest gpr = this.goodDao.queryMgrGoodData(goodid);
		if (gpr == null) return null;
		
		String picturePath = this.fuSettings.getRootVirtual() + this.fuSettings.getGoodpicturePath();
		
		GoodPictureUpdateRequest cp = this.gpDao.queryCoverPictureForUpdate(goodid, picturePath);
		if (cp == null) return null;
		
		gpr.setCoverpicture(cp);
		gpr.setOtherpictures(this.gpDao.queryOtherPictureForUpdate(goodid, picturePath));
		
		return gpr;
	}
	
	/**
	 * 新增/更新商品。
	 * @author Chrise 2021年1月5日
	 * @param data 商品数据。
	 * @param goodpicture 封面图片。
	 * @param goodpictures 更多图片。
	 * @param session 用户会话。
	 * @return 新增/更新结果。
	 */
	public String updateGood(GoodUpdateRequest data, MultipartFile goodpicture, List<MultipartFile> goodpictures, UserSession session) {
		if (this.goodDao.existsGood(session.getOrgid(), data.getGoodname(), data.getGoodcode(), data.getGoodid())) return "商品已存在！";
		
		String goodpicturePath = null;
		if (goodpicture != null) {
			try {
				goodpicturePath = FileUtil.saveFile(goodpicture, this.fuSettings.getRootReal() + this.fuSettings.getGoodpicturePath(), 
						this.fuSettings.getGoodpictureType(), this.fuSettings.getCommonAttachSize());
			} catch (FileUploadException e) {
				switch (e.getFueCode()) {
				case FILE_INVALID:
					return "商品封面图片文件无效！";
				case ILLEGAL_TYPE:
					return "商品封面图片文件类型错误！";
				case TOO_BIG:
					return "商品封面图片文件太大！";
				}
			} catch (Exception e) {
				return "保存商品封面图片文件错误！";
			}
		}
		if (data.getGoodid() == null && goodpicturePath == null) return "商品封面图片文件无效！";
		
		List<String> goodpicturePaths = null;
		if (goodpictures != null && !goodpictures.isEmpty()) {
			try {
				goodpicturePaths = FileUtil.saveFile(goodpictures, this.fuSettings.getRootReal() + this.fuSettings.getGoodpicturePath(), 
					this.fuSettings.getGoodpictureType(), this.fuSettings.getCommonAttachSize());
			} catch (FileUploadException e) {
				switch (e.getFueCode()) {
					case FILE_INVALID:
						return "商品图片文件无效！";
					case ILLEGAL_TYPE:
						return "商品图片文件类型错误！";
					case TOO_BIG:
						return "商品图片文件太大！";
				}
			} catch (Exception e) {
				return "保存商品图片文件错误！";
			}
		}
		
		int entitystate = (data.getGoodprice().doubleValue() == 0.0) ? EntityState.VALID.getValue() : EntityState.ONSALE.getValue();
		
		Goods good = null;
		if (data.getGoodid() == null) {
			good = new Goods(entitystate, session.getOrgid(), data.getGoodname(), data.getGoodcode(), data.getGoodspecs(), 
				data.getMeteringunit(), data.getGoodprice(), data.getManufacturer(), data.getGooddetail());
			this.goodDao.save(good);
		} else {
			good = this.goodDao.getOne(data.getGoodid());
			good.setEntitystate(entitystate);
			good.setGoodname(data.getGoodname());
			good.setGoodcode(data.getGoodcode());
			good.setGoodspecs(data.getGoodspecs());
			good.setMeteringunit(data.getMeteringunit());
			good.setGoodprice(data.getGoodprice());
			good.setManufacturer(data.getManufacturer());
			good.setGooddetail(data.getGooddetail());
		}
		
		if (goodpicturePath != null) {
			Goodpictures cover = new Goodpictures(EntityState.VALID.getValue(), good.getEntityid(), PictureType.COVER.getValue(), goodpicturePath);
			this.gpDao.save(cover);
		}
		
		if (goodpicturePaths != null) {
			for (String path : goodpicturePaths) {
				Goodpictures normal = new Goodpictures(EntityState.VALID.getValue(), good.getEntityid(), PictureType.NORMAL.getValue(), path);
				this.gpDao.save(normal);
			}
		}
		
		if (CommonUtil.isNotEmpty(data.getDeletedpictures())) {
			String[] array = data.getDeletedpictures().split(",");
			for (String pictureid : array) {
				Goodpictures picture = this.gpDao.getOne(Long.valueOf(pictureid));
				picture.setEntitystate(EntityState.DELETED.getValue());
			}
		}
		
		return null;
	}
	
	/**
	 * 删除商品。
	 * @author Chrise 2021年1月11日
	 * @param goodid 商品标识。
	 */
	public void deleteGood(long goodid) {
		Goods good = this.goodDao.getOne(goodid);
		good.setEntitystate(EntityState.DELETED.getValue());
	}
	
	/**
	 * 加载商品浏览列表数据。
	 * @author Chrise 2021年1月16日
	 * @param searcher 商品搜索器。
	 * @param session 用户会话。
	 * @return 商品浏览列表数据。
	 */
	public List<Map<String, Object>> loadViewListData(GoodSearcher searcher, UserSession session) {
		if (searcher.getProvinceid() == null) {
			GoodSearcher gs = this.cybercafeDao.queryCybercafeArea(session.getOrgid());
			searcher.setProvinceid(gs.getProvinceid());
			searcher.setCityid(gs.getCityid());
			searcher.setDistrictid(gs.getDistrictid());
			searcher.setStreetid(gs.getStreetid());
		}
		
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		
		long supplierid = 0L;
		List<ViewListGood> vlgs = null;
		Map<String, Object> map = null;
		List<ViewListGood> all = this.goodDao.queryViewListData(searcher, this.fuSettings.getRootVirtual() + this.fuSettings.getGoodpicturePath());
		for (ViewListGood vlg : all) {
			if (supplierid != vlg.getSupplierid().longValue()) {
				supplierid = vlg.getSupplierid().longValue();
				
				vlgs = new ArrayList<ViewListGood>();
				map = new HashMap<String, Object>();
				map.put("goods", vlgs);
				
				String suppliername = this.supplierDao.querySupplierName(supplierid);
				map.put("name", suppliername);
				
				result.add(map);
			}
			
			vlgs.add(vlg);
		}
		
		return result;
	}
	
	/**
	 * 验证商品。
	 * @author Chrise 2021年1月17日
	 * @param goods 商品标识。
	 * @return 在售商品。
	 */
	public List<ListGood> checkGoods(String goods) {
		String[] array = goods.split(",");
		List<Long> goodids = new ArrayList<Long>();
		for (String goodid : array) {
			goodids.add(Long.valueOf(goodid));
		}
		return this.goodDao.checkGoods(goodids);
	}
	
	/**
	 * 加载商品浏览详情数据。
	 * @author Chrise 2021年1月24日
	 * @param goodid 商品标识。
	 * @return 商品浏览详情数据。
	 */
	public Object loadViewDetailData(long goodid) {
		ViewGoodDetail detail = this.goodDao.queryViewDetailData(goodid);
		if (detail == null) return "商品已下架";
		
		List<String> pictures = this.gpDao.queryGoodPictures(goodid, this.fuSettings.getRootVirtual() + this.fuSettings.getGoodpicturePath());
		detail.setGoodpics(pictures);
		
		return detail;
	}
}
